﻿using StarryEdge.Core.Device;
using StarryEdge.Core.Models;
using StarryEdge.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using StarryEdge.Core.Models.Testers;
using StarryEdge.Devices.MeterDevice.ElectronicScales;
using System.Formats.Asn1;

namespace StarryEdge.Devices.MeterDevice.Testers
{
    public class ST5520 : NormalDeviceBase, IDeviceInteraction<string>
    {
        public ST5520(ICommunication com, IStarryEdgeLog edgeLog, Func<DeviceInfoModel, IDevice, bool> func) : base(com, edgeLog, func)
        {
        }

        public void Close() => _com.Close();
        
        public bool Open() => _com.Open();

        public TValue ReadSingle<TValue>(string address, int length = 3)
        {
            for (int i = 0; i < length; i++)
            {
                try
                {
                    ST5520ResultModel model = new ST5520ResultModel();
                    _com.Send(Encoding.ASCII.GetBytes(":MEASure:RESult?\r\n"));
                    byte[] bytes = _com.Receive();
                    string[] str = Encoding.ASCII.GetString(bytes).Trim().Split(',');
                    model.Test_Value = Convert.ToSingle(str[0]) / 1000000.0F;
                    model.Test_Result = str[1];
                    if (model is TValue s)
                    {
                        return s;
                    }
                    return default;
                }
                catch (Exception ex)
                {
                    _edgeLog.LogRun($"[{nameof(ST5520)}] 异常：{ex}", Core.Enums.LogLevel.Warning);
                    if (_func.Invoke(_com.DeviceInfo, this))
                    {
                        return default;
                    }
                }
            }
            return default;
        }

        public bool WriteSingle(string address, object value, int length)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(address);
            for (int i = 0; i < length; i++)
            {
                try
                {
                    _com.Send(bytes);
                    return true;
                }
                catch (Exception ex)
                {
                    _edgeLog.LogRun($"[{nameof(ST5520)}] 异常：{ex}", Core.Enums.LogLevel.Warning);
                    if (_func.Invoke(_com.DeviceInfo, this))
                    {
                        return default;
                    }
                }
            }
            return false;
        }
    }
}
